package cn.itcast.microservice.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by User on 2018/2/27.
 */
public class UserLoginZuulFilter extends ZuulFilter {
    /**
     * 过滤器的类型
     *
     * @return 返回值即为过滤器的类型
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 执行顺序，值越小，优先级越高
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 过滤器是否需要执行
     *
     * @return true为需要执行，false为不需要执行
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器具体的业务逻辑
     *
     * @return
     */
    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)){
            // 过滤该请求，不对其进行路由
            requestContext.setSendZuulResponse(false);
            // 设置相应状态码
            requestContext.setResponseStatusCode(401);
        }
        return null;
    }
}






























